from flask import abort, jsonify
from flask import current_app
from flask import g
from flask import render_template
from flask import request

from info import constants, db
from info.models import News, Category, Comment, CommentLike
from info.modules.news import news_blu
from info.utils.common import user_login_data
from info.utils.response_code import RET


@news_blu.route('/<int:news_id>')
@user_login_data
def detail(news_id):
    click_news = None
    try:
        click_news = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS ).all()
    except Exception as ret:
        current_app.logger.error(ret)

    news_con = None
    try:
        news_con = News.query.get(news_id)
    except Exception as ret:
        current_app.logger.error(ret)
    if not news_con:
        abort(404)

    is_collected = False
    if g.user:
        # 设置了lazy="dynamic 可以不用all(),新闻与用户与many to many关系
        if news_con in g.user.collection_news:
            is_collected = True

    # 查询新闻ID为news_id的评论
    comments = []
    try:
        comments = Comment.query.filter_by(news_id=news_con.id).order_by(Comment.create_time.desc()).all()
    except Exception as ret:
        current_app.logger.error(ret)


    # 查询当前用户在当前新闻中点赞了那些评论
    # 当前新闻的评论ID
    comment_ids = [comment.id for comment in comments]
    comment_likes = []
    try:
        comment_likes = CommentLike.query.filter(CommentLike.comment_id.in_(comment_ids),Comment.user_id==g.user.id)
    except Exception as ret:
        current_app.logger.error(ret)

    comment_likes_ids = [comment_Like.comment_id for comment_Like in comment_likes]
    comments_list = []
    for comment in comments:
        comment_dict = comment.to_dict()
        comment_dict["is_like"] = False
        if comment.id in comment_likes_ids:
            comment_dict["is_like"] = True
        comments_list.append(comment_dict)



    data = {
        "clicks_news": click_news,
        "user": g.user.to_dict() if g.user else None,
        "news": news_con.to_dict(),
        "is_collected": is_collected,
        "comments": comments_list
    }
    return render_template('news/detail.html',data=data)


@news_blu.route('/news_collect',methods=['POST'])
@user_login_data
def news_collect():
    # 获取参数
    user = g.user
    json_data = request.json
    news_id = json_data.get('news_id')
    action = json_data.get('action')
    # 校验参数
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登陆")
    if not news_id:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if action not in ["cancel_collect","collect"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        news_id = int(news_id)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.DBERR, errmsg="参数错误")
    # 通过新闻ID获取新闻模型
    try:
        news = News.query.get(news_id)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="无新闻数据")

    if action == "collect":
        if news not in user.collection_news:
            user.collection_news.append(news)
    else:
        if news in user.collection_news:
            user.collection_news.remove(news)

    try:
        db.session.commit()
    except Exception as ret:
        current_app.logger.error(ret)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="收藏失败")

        return jsonify(errno=RET.OK, errmsg="收藏成功")


# 新闻评论
@news_blu.route('/news_comment',methods=['POST'])
@user_login_data
def news_comment():
    user = g.user
    json_data = request.json
    news_id = json_data.get("news_id")
    comment = json_data.get("comment")
    parent_id = json_data.get("parent_id")
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登陆")
    if not all([news_id,comment]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    try:
        news_id = int(news_id)
        if parent_id:
            parent_id = int(parent_id)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.DBERR, errmsg="参数错误")

    try:
        news = News.query.get(news_id)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")

    comment_model = Comment()
    comment_model.news_id = news_id
    comment_model.user_id = user.id
    comment_model.content = comment
    if parent_id:
        comment_model.parent_id = parent_id

    # 更新评论数据表
    try:
        db.session.add(comment_model)
        db.session.commit()
    except Exception as ret:
        current_app.logger.error(ret)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存评论数据错误")

    return jsonify(errno=RET.OK, errmsg="ok", data=comment_model.to_dict())


@news_blu.route('/comment_like',methods=['POST'])
@user_login_data
def comment_like():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登陆")
    json_data = request.json
    comment_id = json_data.get("comment_id")
    action = json_data.get("action")

    if not all([comment_id,action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    try:
        comment_id = int(comment_id)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.DBERR, errmsg="参数错误")
    if action not in ["add", "remove"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 查询评论是否存在，防止恶意访问,更新like_count
    try:
        comment = Comment.query.get(comment_id)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.DBERR, errmsg="查询失败")
    if not comment:
        return jsonify(errno=RET.NODATA, errmsg="评论不存在")

    comment_like_model = CommentLike.query.filter(CommentLike.user_id == user.id, CommentLike.comment_id == comment_id).first()
    if action == "add":
        if not comment_like_model:
            comment_like_model = CommentLike()
            comment_like_model.user_id = user.id
            comment_like_model.comment_id = comment_id
            comment.like_count += 1
            db.session.add(comment_like_model)
    else:
        if comment_like_model:
            db.session.delete(comment_like_model)
            comment.like_count -= 1
    try:
        db.session.commit()
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.DBERR, errmsg="保存点赞数据错误")

    return jsonify(errno=RET.OK, errmsg="ok")